package io.renren.socket.client.test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.renren.modules.iotp.entity.IOTPBean;
import io.renren.modules.iotp.entity.IOTPBody;
import io.renren.socket.client.NioAbstractClient;

/**
 * 同步 设备和变量的 socket连接
 * 
 * @author lfy.xys
 * @date 2018年5月22日
 *
 */
public class SyncDataClientRunnable_bak extends NioAbstractClient implements Runnable {

	private static Logger logger = LoggerFactory.getLogger(SyncDataClientRunnable_bak.class);

	public SyncDataClientRunnable_bak(String ip, int port, List<byte[]> sendMsg) {
		super(ip, port, sendMsg);
	}

	@Override
	public void run() {
		try {
			logger.info(ip + ":" + port);
			this.connect();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (client != null) {
				try {
					rBuffer.clear();
					client.close();
					logger.info("关闭 {}:{} 的连接", ip, port);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void sendMsg() {
		int i = 0;
		for (byte[] bs : sendMsg) {
			// 循环发送 socket发送
			try {
				logger.info("发送了{}次", ++i);
				client.write(ByteBuffer.wrap(bs));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * @return 返回值 是否继续 接收 消息
	 */
	@Override
	public boolean receiveMsg(byte[] bytes) {

		IOTPBean iotp = ibu.toIotpBean(bytes);
		IOTPBody body = iotp.getBody();
		if (body != null) {
			// 解析成功
		} else {
			// 不成功，返回true，继续接收消息
			return true;
		}

//		logger.info("body:" + body.toString());
		// 获得协议体
		List<String> list = body.getBodyList();
		String resultMsg = list.toString();
		logger.info("接收到结果：{}", resultMsg);

		// 成功，返回false，停止接收消息，close
		return false;
	}

	
}
